/**
 * 工具类,所有方法放到一个对象中,方便维护命名和定位
 * (PS:注册到JQUERY时命名如果不注意可能冲突)
 * 命名规则:工具+行为
 * @author: ZL
 * @version 1.0.0
 */

/**
 * 异步请求ajax
 * 请求地址：requestUrl
 * JSON对象: params
 * 回调方法: callBack
 */
zUtil.ajaxGet = function(requestUrl, params, callBack) {
    return zUtil.ajaxFunc(requestUrl, params, "GET", callBack, true);
};
zUtil.ajaxPost = function(requestUrl, params, callBack) {
    return zUtil.ajaxFunc(requestUrl, params, "POST", callBack, true);
};
zUtil.ajaxPut = function(requestUrl, params, callBack) {
    return zUtil.ajaxFunc(requestUrl, params, "PUT", callBack, true);
};
zUtil.ajaxDelete = function(requestUrl, params, callBack) {
    return zUtil.ajaxFunc(requestUrl, params, "DELETE", callBack, true);
};
/**
 * 同步请求ajax
 * 请求地址：requestUrl
 * JSON对象: params
 */
zUtil.ajaxGetSync = function(requestUrl, params) {
    return zUtil.ajaxFunc(requestUrl, params, "GET", null, false);
};
zUtil.ajaxPostSync = function(requestUrl, params) {
    return zUtil.ajaxFunc(requestUrl, params, "POST", null, false);
};
zUtil.ajaxPutSync = function(requestUrl, params) {
    return zUtil.ajaxFunc(requestUrl, params, "PUT", null, false);
};
zUtil.ajaxDeleteSync = function(requestUrl, params) {
    return zUtil.ajaxFunc(requestUrl, params, "DELETE", null, false);
};
/**
 * 自行传参,默认异步
 * options：参数配置对象{}
 */
zUtil.ajaxGetCustom = function(options) {
    options.type = "GET";//强制设置为GET
    return zUtil.ajaxCustomFunc(options);
};
zUtil.ajaxPostCustom = function(options) {
    options.type = "POST";//强制设置为POST
    return zUtil.ajaxCustomFunc(options);
};
zUtil.ajaxPutCustom = function(options) {
    options.type = "PUT";//强制设置为PUT
    return zUtil.ajaxCustomFunc(options);
};
zUtil.ajaxDeleteCustom = function(options) {
    options.type = "DELETE";//强制设置为DELETE
    return zUtil.ajaxCustomFunc(options);
};
//ajax固定传参
zUtil.ajaxFunc = function(requestUrl, params, method, callBack, sync) {
    zUtil.progress();
    var data = null;
    var opts =  {
            type: method,
            url: requestUrl,
            data: {},
            dataType: "json",
            contentType : "application/json;charset=utf-8",
            cache : false,
            async : sync,
            success: function(result,status,xhr){
                if(callBack){//有回调方法
                    callBack(result);//自行处理
                }else{
                    data = result;
                }
            },
            beforeSend: function(){
            },
            complete: function(){
                zUtil.progress("close");
            }
      };
    
    if(params){
        var queryStr = params;
        if(opts.type == "GET"){
            opts.contentType = null;
        }
        else if(opts.contentType && opts.contentType.indexOf("json")!==-1 && $.type(queryStr) !== "string"){
            queryStr = JSON.stringify(queryStr);//参数带上JSON.stringify();
        }
        else if(opts.type == "POST"){
            console.log(opts.contentType);
//          queryStr = $.param(queryStr);//转换为查询字符串
            opts.contentType = "application/x-www-form-urlencoded;charset=utf-8";
        }
        opts.data = queryStr;
    }
    
    $.ajax(opts);
    return data;//ajaxs.responseJSON;
};

zUtil.ajaxFunc2 = function(requestUrl, params, method, callBack, sync) {
  zUtil.progress();
  var data = null;
  var opts = {
    method: method,
    headers: {
      "Content-Type": "application/json;charset=utf-8"
    },
    cache: "no-cache",
    mode: "cors",
    redirect: "follow",
    referrerPolicy: "no-referrer",
    body: null
  };

  if (params) {
    if (method === "GET") {
      requestUrl += "?" + new URLSearchParams(params).toString();
    } else {
      opts.body = JSON.stringify(params);
    }
  }

  fetch(requestUrl, opts)
    .then(function(response) {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      data=response.json();
      return data;
    })
    .then(function(data) {
      if (callBack) {
        callBack(data);
      }
      zUtil.progress("close");
    })
    .catch(function(error) {
      console.error("Error:", error);
    });
};

//ajax自定传参
zUtil.ajaxCustomFunc = function(options) {
    if(options.msgFlag){
        zUtil.progress();
    }
    var data = null;
    var opts =  $.extend(true,{
            type: '',//GET/POST/PUT/DELETE
            url: '',
            data: {},
            dataType: "json",
            contentType : "application/json;charset=utf-8",
            cache : false, //false:不缓存
            async : true, //false:同步
//            beforeSend:function(xhr){//发送请求前可修改 XMLHttpRequest 对象的函数
//                //add code
//            },
//            dataFilter:function(data,type){// // 对Ajax返回的原始数据进行预处理
//                //add code
//            },
            success: function(result,status,xhr){
                data = result;
            },
            beforeSend: function(){
            },
            complete: function(){
                if(options.msgFlag){
                    zUtil.progress("close");
                }
           }
        }, options);
    if(opts.data){
        var queryStr = opts.data;
        if(opts.type == "GET"){
            opts.contentType = null;
        }
        else if(opts.contentType && opts.contentType.indexOf("json")!==-1 && $.type(queryStr) !== "string"){
            queryStr = JSON.stringify(queryStr);//参数带上JSON.stringify();
        }
        else if(opts.type == "POST"){
//          queryStr = $.param(queryStr);//转换为查询字符串
            opts.contentType = "application/x-www-form-urlencoded;charset=utf-8";
        }
        opts.data = queryStr;
    }
    
    $.ajax(opts);
    return data;//ajaxs.responseJSON;
};
zUtil.ajaxForm = function(id,options,callback){
    var opts = $.extend(true,{
        url: '',
        type: 'post',  
        dataType: 'json',        // 'xml', 'script', or 'json' (expected server response type)
        clearForm: true,        // clear all form fields after successful submit
        resetForm: true,        // reset the form after successful submit
        async: true,         //异步
//      timeout:   3000,
//      target:        '#output1',   // target element(s) to be updated with server response
//      beforeSubmit: function(formData, jqForm, options) {},  
        success: function(responseText, statusText, xhr, form){
            callback(responseText);
        },
        error: function(xhr, status, err) {
            
        },
    }, options);
    $(id).ajaxSubmit(opts);
}
zUtil.ajaxForm2 = function(id,options){
    const form = document.getElementById(id);
    const formData = new FormData(form);
    fetch(options.url, {
        method: 'POST',
        body: formData,
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
}

zUtil.getUrlParams = function(){
       var url = location.search; //获取url中"?"符后的字串  
       var theRequest = {};  
       if (url.indexOf("?") != -1) {  
          var str = url.substr(1);  
          strs = str.split("&");  
          for(var i = 0; i < strs.length; i ++) {  
             theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);  
          }  
       }  
       return theRequest;   
};


//uuid
zUtil.uuid = function(){
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
        });
};
//uuid
zUtil.uuidstr = function(){
    return zUtil.uuid().replace(new RegExp('-','g'),'');
};


/**
 * 根据名字获取对象值，简化多级判断，默认没有则返回null
 * object         数据对象 {}
 * path           路径 result.data.data或result.data.data[],result.data.data[0]
 * defaultValue   查找为空时的默认值,一般需要用到null或""
 */
zUtil.getVal = function(object, path, defaultValue) {
    var value = null;
        if(!$.isEmptyObject(object) && "object" === $.type(object) && path){
            var paths = path.split('.');
            var length = paths.length;
            $.each(paths,function(i,v){
                var aidx = v.lastIndexOf("[");
                if(aidx > 0){
                    //如果结构不匹配数组,则直接返回null
                    if("array" === $.type(object)){
                        var name = v.substring(0,aidx);
//                        console.log(name);
                        var sidx= v.substring(aidx+1,v.lastIndexOf("]"))
                        if(!sidx){//取全部数组
                            var tmp = [];
                            for(var oi=0,ln = object.length;oi < ln; oi++){
                                tmp.push((object[oi])[name]);
                            }
                            object = tmp;
                        }else{
                            object = (object[sidx])[name];
                        }
                        if(length-1 == i && "undefined" !== $.type(object)){
                            value = object;
                        }
                        if("object" !== $.type(object) && "array" !== $.type(object)){
                            return false;
                        }
                    }else{
                        return false;
                    }
                }else{
                    object = object[v];
                    
                    if(length-1 == i && "undefined" !== $.type(object)){
                        value = object;
                    }
                    if("object" !== $.type(object) && "array" !== $.type(object)){
                        return false;
                    }
                }
            });
        }
        if(value == null && "undefined" !== $.type(defaultValue)){
            value = defaultValue;
        }
        return value;
};
/**对象取值/赋值**/
zUtil.deepVal = function(object, path, defaultValue) {
    path = ("array" !== $.type(path)) ? path.replace(/\[/g, '.').replace(/\]/g, '').split('.') : path;
    
    //根据路径创建对象
    const createObject = (path, value) => {
      let keyPath = [];
      if ("array" === $.type(path)) {
          keyPath = [...path];
      }
      if (keyPath.length) {
        const key = keyPath.shift();
        if ("number" === $.type(key)) {
          const object = new Array(key + 1);
          object[key] = createObject(keyPath, value);
          return object;
        } else{
            return { [key]: createObject(keyPath, value) };
        }
      } else{
          if("array" === $.type(value)){
              return $.extend(true,[], value);
          }
          else if("object" === $.type(value)){
              return $.extend(true,{}, value);
          }
          else{
              return value;
          }
      }
    };
    // 根据路径赋值
    const setPathValue = (object, path, value) => {
      let keyPath = [];
      if ("array" === $.type(path)){
          keyPath = [...path];
      }
      if (keyPath.length) {
        const key = keyPath.shift();
        if (object && object[key]){
            object[key] = setPathValue(object[key], keyPath, value);
        }
        else{
            object[key] = createObject(keyPath, value);
        }
      } else{
          if("array" === $.type(value)){
              object = $.extend(true,[], value);
          }
          else if("object" === $.type(value)){
              object = $.extend(true,{}, value);
          }
          else{
              object = value;
          }
      }
      return object;
    };
    // 根据路径取值
    const getPathValue = (object, path) => {
      let keyPath = [];
      if ("array" === $.type(path)){
          keyPath = [...path];
      }
      else if ("string" === $.type(path) || "number" === $.type(path)){
          keyPath = [path];
      }
      while (keyPath.length) {
        const key = keyPath.shift();
        if (!object){
            return undefined;
        }
        object = object[key];
      }
      return object;
    };
    
    if("undefined" !== $.type(defaultValue)){
      return setPathValue(object, path, defaultValue);
    }else{
      return getPathValue(object, path);
    }
};


zUtil.parse = function(obj,option) {
    var opts = $.extend({
        flag: false,
    },option);
    try{
       if(!opts.flag){
          return JSON.parse(obj);
       }else{
          var result = JSON.parse(obj,function(k,v){
              if(v.indexOf && v.indexOf('function') > -1){
                  return null;
              }
              return v;
          });
          return result;
       }
   }catch(b){
       console.log(b);
       return null;
   }
}
zUtil.strify = function(obj,option) {
    var opts = $.extend(true,{
        flag: false,
        indent: 4,
        indentFlag: false,
    },option);
    try{
       if(!opts.flag){
           if(!opts.indentFlag){
               return JSON.stringify(obj);
           }else{
               return JSON.stringify(obj,null,opts.indent);
           }
       }else{
           var result =JSON.stringify(obj, function(key, val) {
                if (typeof val === 'function') {
                  return val +'';
                }
                return val;
           });
           return result;
       }
   }catch(b){
       console.log(b);
       return null;
   }
}
zUtil.clip = function(id,options) {
     var clipboard = new ClipboardJS(id);
     
     if("undefined" != $.type(options) && options.success){
         clipboard.on('success', options.success);
     }else{
         clipboard.on('success', function(e) {
             var msg = "已复制";
             if("undefined" === $.type(options) || options.show){
                 msg = msg +" "+ e.text;
             }
             zUtil.Toastr("success",msg + e.text);
             e.clearSelection();
         });
     }
     if("undefined" != $.type(options) && options.error){
         clipboard.on('error', options.error);
     }else{
       clipboard.on('error', function(e) {
           zUtil.Toastr("error","复制失败");
           e.clearSelection();
       });
     }
     return clipboard;
}
zUtil.fillstr = function(str,ln,fchar,type) {
   if(!fchar){
       fchar = "0";
   }
   if(!type){
       type = "L"; // L或R
   }
   if(!ln){
       ln = 5; // L或R
   }
   if(!str){
       return str;
   }
   var sn = str.toString().length;
   if(sn < ln){
      for(var fn=ln-sn;fn>0;fn--){
           if(type==='L'){
               str =  fchar + str;
           }else if(type==='R'){
               str = str + fchar;
           }
      }
   }
   return str;
}
zUtil.arrayToTree = function(data,idKey,pidKey,childKey) {
    // 空数组
    let result = [];
    // 判断不是数组直接返回
    if (!Array.isArray(data)) {
        return result
    }
    // 遍历删除  children 属性做初始化操作
    data.forEach(item =>{
        delete item[childKey];
    });
    //  空对象
    let map = {};
    data.forEach(item =>{
        map[item[idKey]] = item;
    });
    data.forEach(item =>{
        // item.pid 为0时返回underfined
        let parent = map[item[pidKey]];
        if (parent) { (parent[childKey] || (parent[childKey] = [])).push(item);
        } else {
            // 这⾥push的item是pid为0的数据
            result.push(item);
        }
    });
    return result;
}
/**
 * 分组统计
 * @param datas 数据集合
 * @param keys 分组键值
 * @param callback 回调函数(例如求和还是计算总数)
 * @returns {{}}
 */
zUtil.groupBy=function(datas,keys,callback) {
    var groups = {};
    var len = keys.length;
    datas.forEach(function (data){
        var tempObj = null;
        keys.forEach(function (key,index){
            var val = data[key];
            if(tempObj == null){
                tempObj = groups;
            }
            //最后一个元素赋值操作
            if(index == len - 1){
                var cal = 0;
                if(tempObj.hasOwnProperty(val)){
                    cal = tempObj[val];
                }
                tempObj[val] = callback(cal,data);
            }else{
                if(tempObj.hasOwnProperty(val)){
                    tempObj = tempObj[val];
                }else{
                    tempObj[val] = {};
                    tempObj = tempObj[val];
                }
            }
        })

    });
    return groups;
}
/**
 * 屏蔽默认的右键菜单即可onload="noright(document.body);"
 */
function noright(obj) {
    if (!obj) {
      return;
    }
    try {
        obj.oncontextmenu  =  function() {
            return false;
        }
        obj.ondragstart  =  function() {
            return false;
        }
    }catch(e){
    }
}

/**
* 去掉字符串头尾空格
* @param str 传入的字符串值
* @author lqy
* @since 2015-08-21
*/ 
zCheck.trim = function(str) {
    if(str == null){ 
        return ""; 
    } 
    return str.replace(/(^\s*)|(\s*$)/g, ""); 
}; 
   
/** 
 * 是否为Null 
 * @param object 
 * @returns {Boolean} 
 */   
zCheck.isNull = function(object){
    if(object == null || typeof object == "undefined"){   
        return true;   
    }   
    return false;
};  
   
/** 
 * 是否为空字符串，有空格不是空字符串 
 * @param str 
 * @returns {Boolean} 
 */   
zCheck.isEmpty = function(str){
    if(str == null || typeof str == "undefined" ||    
            str == ""){   
        return true;   
    }   
    return false;   
}; 
   
/** 
 * 是否为空字符串，全空格也是空字符串 
 * @param str 
 * @returns {Boolean} 
 */   
zCheck.isBlank = function(str){
    if(str == null || typeof str == "undefined" ||    
            str == "" || trim(str) == ""){   
        return true;   
    }   
    return false;   
};
/**
 * 检查手机号码
 * @param z_check_value 要检查的值
 * @return 符合返回true，否false
 * @since 2015-08-21
*/ 
zCheck.isPhone = function(z_check_value) { 
    if(isEmpty(z_check_value) || z_check_value.length != 11){ 
        return false; 
    } 
    var z_reg = /^13[0-9]{9}|15[012356789][0-9]{8}|18[0-9]{9}|(14[57][0-9]{8})|(17[015678][0-9]{8})$/; 
    return z_reg.test(z_check_value); 
};  
/**
 * 检查电子邮箱
 * @param z_check_value 要检查的值
 * @return 符合返回true，否false
 * @since 2015-08-21
*/ 
zCheck.isEmail = function(z_check_value){ 
    //var emailReg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; 
    var z_reg =  /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/; 
    return z_reg.test($.trim(z_check_value)); 
};  
/**
 * 检查编码（由数字、26个英文字母或者下划线组成的字符串）
 * @param z_check_value 要检查的值
 * @return 符合返回true，否false
 * @since 2015-12-29
*/ 
zCheck.isNo = function(z_check_value){ 
    var z_reg = /^\w+$/; 
    return z_reg.test($.trim(z_check_value)); 
};
zCheck.isLetterNum = function(z_check_value){ 
    var z_reg = /^[A-Za-z]+[0-9]{0,}$/; 
    return z_reg.test($.trim(z_check_value)); 
};
zCheck.isLetterNumx = function(z_check_value){ 
    var z_reg = /^[A-Za-z]+[0-9]{0,}(,[A-Za-z]+[0-9]{0,})*$/; 
    return z_reg.test($.trim(z_check_value)); 
};
/**
 * 检查电话号码
 * @param z_check_value 要检查的值
 * @return 符合返回true，否false
 * @since 2015-08-21
*/ 
zCheck.isTelePhone = function(z_check_value){ 
    var z_reg = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,4}))?$/; 
    return z_reg.test($.trim(z_check_value)); 
};  
/**
 * 检查仅中文
 * @param z_check_value 要检查的值
 * @return 符合返回true，否false
 * @since 2015-08-21
*/ 
zCheck.isChinese = function(z_check_value){
    var z_reg = /^[\u4E00-\u9FA5\uF900-\uFA2D]+$/; 
    return z_reg.test($.trim(z_check_value)); 
};  
/**
 * 是否为数字
 * @param z_check_value 要检查的值
 * @return 符合返回true，否false
 * @since 2016-10-31
*/ 
zCheck.isNumber = function(z_check_value){ 
    var z_reg = /^(([0-9])|([1-9]([0-9]+)))$/; 
    return z_reg.test($.trim(z_check_value)); 
};  
/**
 * 是否为数字组成的字符串，01也符合规则
 * @param z_check_value 要检查的值
 * @return 符合返回true，否false
 * @since 2017-01-07
*/ 
zCheck.isNumberText = function(z_check_value){ 
    var z_reg = /^([0-9]+)$/; 
    return z_reg.test($.trim(z_check_value)); 
};  
/**
 * 可以判断是否为数字、金额、浮点数
 * @param z_check_value 要检查的值
 * @return 符合返回true，否false
 * @author lqy
 * @since 2017-01-07
*/
zCheck.isFloat = function(z_check_value){ 
    var z_reg = /^((([0-9])|([1-9][0-9]+))(\.([0-9]+))?)$/;//.是特殊字符，需要转义 
    return z_reg.test($.trim(z_check_value)); 
};
/** 匹配java包路径*/
zCheck.isPackagePath = function(z_check_value){ 
    var z_reg = new RegExp("^[a-z]+[a-z0-9]*(\\.[a-z]+[a-z0-9]*)*$",'ig');
    return z_reg.test($.trim(z_check_value)); 
};
/** 匹配java包路径*/
zCheck.isPackagePathx = function(z_check_value){
    var z_reg = new RegExp("(^[a-z]+[0-9]{0,}$)|(^\\{[a-z]+_[a-z0-9]+\\}$)",'ig');
    return z_reg.test($.trim(z_check_value)); 
};
/** 匹配文件路径*/
zCheck.isFilePath = function(z_check_value){ 
    var z_reg = new RegExp("(^/[a-z]+[-_\\.a-z0-9]*(/[a-z]+[-_\\.a-z0-9]*)*/{0,1}$)" +
            "|^/\\{[a-z]+_[a-z0-9]+\\}(/\\{[a-z]+_[a-z0-9]+\\})*/{0,1}$",'ig');
    return z_reg.test($.trim(z_check_value)); 
};
/** 字典编码规则*/
zCheck.isDictType = function(z_check_value){ 
    var z_reg = new RegExp("^[a-z0-9]+([\\.\\-_]{1}[a-z-0-9]+)*$",'ig');
    return z_reg.test($.trim(z_check_value)); 
};
/**表编码规则*/
zCheck.isTableCode = function(z_check_value){ 
    var z_reg = new RegExp("^[a-z]+[0-9]*(_[a-z0-9]+)*$",'ig');
    return z_reg.test($.trim(z_check_value)); 
};
/**JAVA编码规则(驼峰)*/
zCheck.isJavaCode = function(z_check_value){
    var z_reg = new RegExp("^[a-z]{2,}[0-9]*([A-Z]{1}[a-z]+[0-9]*)*$",'g');
    return z_reg.test($.trim(z_check_value)); 
};
/**表字段编码规则(可带下划线)*/
zCheck.isColumnCode = function(z_check_value){
    var z_reg = new RegExp("^[a-z]{2,}[0-9]*(_[a-z]{2,}[0-9]*)*$",'ig');
    return z_reg.test($.trim(z_check_value)); 
};
/**字段长度格式*/
zCheck.isNumCharCode = function(z_check_value){
    var z_reg = new RegExp("^[0-9]+( *[a-z])*$",'ig');
    return z_reg.test($.trim(z_check_value)); 
};
(function($){
    $.ajaxSetup({
        headers : getHeaderToken(),
        timeout: 60000, //超时时间：30秒 
        error : function(xhr,status,error) {
            try{
                 zUtil.progress("close");
            }catch(b){}
//            console.log(xhr.status);
            if(xhr.status === 503){
//              zUtil.Toastr("error","请求处理失败");
            }
            return;
        },
    });
    
    $(document).ready(function(){
        //禁用拖拽
        $("body").on("dragstart","a,img,button,input[type=button],li",function(e){
            if($(e).parents("z-drag").length == 0){
              return false;
            }
        });
    });
    
    $.extend($.fn.validatebox.defaults.rules, {
        // filebox验证文件大小的规则函数
        // 如：validType : ['fileSize[1,"MB"]']
        fileSize : {
            validator : function(value, array) {
                var size = array[0];
                var unit = array[1];
                var accept = array[2];
                if (!size || isNaN(size) || size == 0) {
                    $.error('验证文件大小的值不能为 "' + size + '"');
                } else if (!unit) {
                    $.error('请指定验证文件大小的单位');
                }
                var index = -1;
                var unitArr = new Array("bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb");
                for (var i = 0; i < unitArr.length; i++) {
                    if (unitArr[i] == unit.toLowerCase()) {
                        index = i;
                        break;
                    }
                }
                if (index == -1) {
                    $.error('请指定正确的验证文件大小的单位：["bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"]');
                }
                // 转换为bytes公式
                var formula = 1;
                while (index > 0) {
                    formula = formula * 1024;
                    index--;
                }
                //console.log(formula);
                // this为页面上能看到文件名称的文本框，而非真实的file
                // $(this).next()是file元素
                return $(this).next().get(0).files[0].size < parseFloat(size) * formula;
            },
            message : '文件大小必须小于 {0}{1}'
        },
        phone : {//手机号码校验 
            validator: function(value, param){ 
                return zCheck.isPhone(value); 
            }, 
            message: '请输入正确的手机号码。' 
        }, 
        myEmail : {//邮箱校验，避免使用email和默认的冲突 
            validator: function(value, param){ 
                return zCheck.isEmail(value); 
            }, 
            message: '请输入正确的邮箱' 
        }, 
        loginName : {//登录名，数字、英文字母或者下划线 
            validator: function(value, param){ 
                return zCheck.isNo(value); 
            }, 
            message: '只能输入数字、英文字母或者下划线' 
        }, 
        letterNum : {//数字、英文字母 
            validator: function(value, param){ 
                return zCheck.isLetterNum(value); 
            }, 
            message: '只能输入英文字母、数字,字母开头' 
        }, 
        letterNumx : {//数字、英文字母 
            validator: function(value, param){ 
                return zCheck.isLetterNumx(value); 
            }, 
            message: '只能输入英文字母、数字,字母开头' 
        }, 
        letterModule : {//数字、英文字母 
            validator: function(value, param){
                if(value){
                   value=value.replace(new RegExp("\n| ","g"),"");
                }
                return zCheck.isLetterNumx(value); 
            }, 
            message: '只能输入英文字母、数字,字母开头' 
        },
        telePhone : {//座机，区号及分机号可有可无 
            validator: function(value, param){ 
                return zCheck.isTelePhone(value); 
            }, 
            message: '请输入正确的座机号码' 
        }, 
        chinese : {// 
            validator: function(value, param){ 
                return zCheck.isChinese(value); 
            }, 
            message: '只能输入中文汉字' 
        }, 
        number : {//正整数，包括0（00，01非数字） 
            validator: function(value, param){ 
                return zCheck.isNumber(value); 
            }, 
            message: '只能输入数字' 
        }, 
        numberText : {//数字组成的字符串，如000222，22220000，00000 
            validator: function(value, param){ 
                return zCheck.isNumberText(value); 
            }, 
            message: '只能输入数字字符串' 
        }, 
        idCardNo : {//身份证 
            validator: function(value, param){ 
                return zCheck.isIdCardNo(value); 
            }, 
            message: '请输入正确的身份证号码' 
        }, 
        money : {//金额 
            validator: function(value, param){ 
                return zCheck.isFloat(value); 
            }, 
            message: '请输入正确的数字' 
        }, 
        floatNumber : {//数字（包括正整数、0、浮点数） 
            validator: function(value, param){
                return zCheck.isFloat(value); 
            }, 
            message: '请输入正确的数字' 
        }, 
        minLength: {
            validator: function(value, param){
                return value.length >= param[0]; 
            },
            message: '请输入至少 {0}个字符。' 
        }, 
        maxLength: {
            validator: function(value, param){
                return value.length <= param[0]; 
            },
            message: '不能输入超过{0}个字符。' 
        },
        packagePath : {//java包路径
            validator: function(value, param){ 
                return zCheck.isPackagePath(value); 
            }, 
            message: 'java路径格式: com.a.b' 
        },
        packagePathx : {//java包路径
            validator: function(value, param){ 
                return zCheck.isPackagePathx(value); 
            }, 
            message: 'java路径格式: console' 
        },
        filePath : {//文件路径
            validator: function(value, param){ 
                return zCheck.isFilePath(value); 
            }, 
            message: '文件路径格式: /p1/p2/p3' 
        },
        dictType : {//字典编码
            validator: function(value, param){ 
                return zCheck.isDictType(value); 
            }, 
            message: '编码格式: 字母或数字，可以使用.-_分隔，a.b-c_d' 
        },
        tableCode : {//表编码
            validator: function(value, param){
                return zCheck.isTableCode(value); 
            }, 
            message: '编码格式: tbl_user' 
        },
        javaCode : {//JAVA字段编码规则(驼峰)
            validator: function(value, param){
                return zCheck.isJavaCode(value); 
            }, 
            message: '编码格式: userCode' 
        },
        columnCode : {//表字段字段编码规则
            validator: function(value, param){
                return zCheck.isColumnCode(value); 
            }, 
            message: '编码格式: user_code' 
        },
        numChar : {
            validator: function(value, param){
                return zCheck.isNumCharCode(value); 
            }, 
            message: '长度格式: 10' 
        },
    });
    
    $.extend($.fn.datagrid.defaults.editors, {
        switchbox: {
            init: function(container, options){
                var input = $('<input />').appendTo(container);
                var opts = $.extend(true, {
                    checked:false,
                    handleText:' ',
                    width:60,
                    height:25,
                    handleWidth:25,
                    value:"0",
                    off:"0",
                    on:"1",
                    offText:"否",
                    onText:"是",
                    data:[{"value":"0","text":"否"}, {"value":"1","text":"是"}],
                    onChange:function(checked){
                        if(checked){
                           $(this).switchbutton("setValue",$(this).switchbutton("options").on);
                        }else{
                           $(this).switchbutton("setValue",$(this).switchbutton("options").off);
                        }
                    }
                }
                ,options);
                input.switchbutton(opts);
//                $.parser.parse(input.parent());
                return input;
            },
            getValue: function(target){
                var opts = $(target).switchbutton('options');
                return $(target).val();
            },
            setValue: function(target, value){
                var opts = $(target).switchbutton("options");
                if(value === opts.on){
                    $(target).switchbutton("check");
                }else{
                    if(!value || value == null){
                        value = opts.off;
                    }
                    $(target).switchbutton("uncheck");
                }
                $(target).switchbutton("setValue",value);
            },
            resize: function(target, width){
                var input = $(target);
                if ($.boxModel == true){
                    input.width(width - (input.outerWidth() - input.width()));
                } else {
                    input.width(width);
                }
            }
        }
    });
   
//    console.log($.fn.datagrid.defaults.editors);
//    console.log($.fn.switchbutton.defaults);
}(jQuery));